package com.atguigu.gulimail.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

//最后处理的数据都以json的方式返回
//@ResponseBody
//@ControllerAdvice(basePackages = {"com.atguigu.gulimail.product.controller"})
@RestControllerAdvice(basePackages = {"com.atguigu.gulimail.product.app"})
@Slf4j
public class GulimailExceptionControllerAdvice {

    @ExceptionHandler(value = {org.springframework.web.bind.MethodArgumentNotValidException.class})
    public R handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {

        log.info("错误消息：{},错误类型：{}", e.getMessage(), e.getClass());
        //如果知道指定的错误类型就可以获取到bindingResult
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) -> {
            map.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCPETION.getCode(), BizCodeEnum.VALID_EXCPETION.getMsg()).put("data", map);
    }

    @ExceptionHandler
    public R handlerException(Throwable throwable) {

        log.error("err tips", throwable);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg()+"JSR303校验异常。")
                .put("data", throwable.getMessage());
    }


}
